package com.lunasoft.dp;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author Jierry
 * @version 2016/7/12.
 */
public class AOPHandler implements InvocationHandler {

    private Object obj; //接口的实现类
    private boolean flag;

    public AOPHandler(Object obj) {
        this.obj = obj; //指定接口实现类
    }

    public void setFlag(Map<String, String> config) {
        if (null == config) {
            flag = false;
        } else {
            if (config.containsKey("transaction") && "true".equalsIgnoreCase(config.get("transaction"))) {
                flag = true;
            } else {
                flag = false;
            }
        }
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (flag) {
            doBefore();
        }
        System.out.println(proxy.getClass().getSimpleName()); //proxy实际上就是动态代理类$Proxy0
        Object result = method.invoke(obj, args); //
        if (flag) {
            doAfter();
        }
        return result;
    }

    private void doBefore() {
        System.out.println("Transaction start...");
    }

    private void doAfter() {
        System.out.println("Transaction commit...");
    }
}
